//+------------------------------------------------------------------+
//|                                                      MultiMA.mq5 |
//|                        Copyright 2023, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"

input ulong         MagicNumber = 666;       // EA魔术编码
input ENUM_TIMEFRAMES Timeframe1 = PERIOD_M1; // 时间周期1
input ENUM_TIMEFRAMES Timeframe2 = PERIOD_M5; // 时间周期2
input ENUM_TIMEFRAMES Timeframe3 = PERIOD_M15;// 时间周期3
input int           MAPeriod1 = 9;           // MA周期1
input int           MAPeriod2 = 34;          // MA周期2

// 指标句柄数组 [时间框架][MA周期]
int handles[3][2];
datetime lastBarTime;

// 新增的3个全局变量名称
string gvMA1Status = "MA_Status_TF1_" + string(MagicNumber);
string gvMA2Status = "MA_Status_TF2_" + string(MagicNumber);
string gvMA3Status = "MA_Status_TF3_" + string(MagicNumber);

//+------------------------------------------------------------------+
//| 获取时间框架字符串                                                |
//+------------------------------------------------------------------+
string GetTFString(ENUM_TIMEFRAMES tf) {
   switch(tf) {
      case PERIOD_M1:  return "M1";
      case PERIOD_M5:  return "M5";
      case PERIOD_M15: return "M15";
      default:         return "TF"+string(tf);
   }
}

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit() {
   // 初始化指标句柄
   ENUM_TIMEFRAMES tf[3] = {Timeframe1, Timeframe2, Timeframe3};
   int periods[2] = {MAPeriod1, MAPeriod2};
   
   for(int i=0; i<3; i++) {
      for(int j=0; j<2; j++) {
         handles[i][j] = iMA(Symbol(), tf[i], periods[j], 0, MODE_SMA, PRICE_CLOSE);
         if(handles[i][j] == INVALID_HANDLE) {
            Print("Error creating MA(", periods[j], ") for ", GetTFString(tf[i]), 
                  " Error: ", GetLastError());
            return INIT_FAILED;
         }
      }
   }
   
   // 初始化全局变量（仅当所有3个变量都不存在时才初始化）
   if(!GlobalVariableCheck(gvMA1Status) && !GlobalVariableCheck(gvMA2Status) && !GlobalVariableCheck(gvMA3Status)) {
      GlobalVariableSet(gvMA1Status, -1);
      GlobalVariableSet(gvMA2Status, -1);
      GlobalVariableSet(gvMA3Status, -1);
      Print("多空初始化全局变量为-1");
   }
   else {
      Print("多空检测到已有全局变量，跳过初始化");
   }
   
   lastBarTime = iTime(Symbol(), Period(), 0);
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
   // 释放所有指标句柄
   for(int i=0; i<3; i++) {
      for(int j=0; j<2; j++) {
         if(handles[i][j] != INVALID_HANDLE) {
            IndicatorRelease(handles[i][j]);
         }
      }
   }
   
   // 删除全局变量（可选）
   //GlobalVariableDel(gvMA1Status);
   //GlobalVariableDel(gvMA2Status);
   //GlobalVariableDel(gvMA3Status);
}

//+------------------------------------------------------------------+
//| 处理新K线的函数                                                   |
//+------------------------------------------------------------------+
void ProcessNewBar(datetime currentTime) {
   ENUM_TIMEFRAMES tf[3] = {Timeframe1, Timeframe2, Timeframe3};
   int periods[2] = {MAPeriod1, MAPeriod2};
   double maValues[3][2]; // 存储所有MA值 [时间框架][MA周期]
   
   // 获取所有MA值
   for(int i=0; i<3; i++) {
      for(int j=0; j<2; j++) {
         double ma[1];
         if(CopyBuffer(handles[i][j], 0, 1, 1, ma) == 1) {
            maValues[i][j] = ma[0];
            string varName = StringFormat("MA_%s_%d_%d", GetTFString(tf[i]), periods[j], MagicNumber);
            GlobalVariableSet(varName, ma[0]);
         }
      }
   }
   
   // 设置3个全局状态变量
   GlobalVariableSet(gvMA1Status, maValues[0][0] > maValues[0][1] ? 1 : 0); // 时间周期1的状态
   GlobalVariableSet(gvMA2Status, maValues[1][0] > maValues[1][1] ? 1 : 0); // 时间周期2的状态
   GlobalVariableSet(gvMA3Status, maValues[2][0] > maValues[2][1] ? 1 : 0); // 时间周期3的状态
   
   // 打印所有存储的值和状态
   Print("===== 时间：", TimeToString(currentTime), " =====");
   for(int i=0; i<3; i++) {
      for(int j=0; j<2; j++) {
         string varName = StringFormat("MA_%s_%d_%d", GetTFString(tf[i]), periods[j], MagicNumber);
         double value = GlobalVariableGet(varName);
         Print(GetTFString(tf[i]), " MA", periods[j], " = ", value);
      }
      // 打印每个时间周期的状态
      string statusVar = (i == 0) ? gvMA1Status : (i == 1) ? gvMA2Status : gvMA3Status;
      int status = (int)GlobalVariableGet(statusVar);
      Print(GetTFString(tf[i]), " 状态: MA", periods[0], " ", (status == 1 ? ">" : "<="), " MA", periods[1]);
   }
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick() {
   datetime currentTime = iTime(Symbol(), Period(), 0);
   
   // 仅在新K线开始时处理
   if(currentTime > lastBarTime) {
      lastBarTime = currentTime;
      ProcessNewBar(currentTime);
   }
}
//+------------------------------------------------------------------+